////////////////////////////////////////////////////////////////////////////////////////////////////////	
//	ADOBE SYSTEMS INCORPORATED																		  //
//	Copyright 2011 Adobe Systems Incorporated														  //
//	All Rights Reserved.																			  //
//																									  //
//	NOTICE:  Adobe permits you to use, modify, and distribute this file in accordance with the		  //
//	terms of the Adobe license agreement accompanying it.  If you have received this file from a	  //
//	source other than Adobe, then your use, modification, or distribution of it requires the prior	  //
//	written permission of Adobe.																	  //
////////////////////////////////////////////////////////////////////////////////////////////////////////

// Modified by Christoph Ketzler
// Modifications are published under the MIT License
/*
 Copyright (c) 2012, Christoph Ketzler
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met: 
 
 1. Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer. 
 2. Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution. 
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
#import "FlashRuntimeExtensions.h"
#import <CoreMotion/CoreMotion.h>
#import <math.h>

CMMotionManager* motionManager = nil;
NSOperationQueue* opQ = nil;


// startGyro() 
//
// Called from the ActionScript constructor of class Gyroscope.

FREObject KTZEulerGyrostartGyro(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[]) {

    //NSLog(@"Entering startGyro()");
	
    BOOL ret = NO;
	FREObject retVal;
    
	if (motionManager != nil) {
    
		if (motionManager.gyroAvailable) {
            /*
            CMGyroHandler gyroHandler = ^ (CMGyroData *gyroData, NSError *error) {
                
                if (ctx != nil) {
                    CMRotationRate rotate = gyroData.rotationRate;
                    NSString *myStr = [NSString stringWithFormat:@"%f&%f&%f",rotate.x,rotate.y,rotate.z]; 
                    NSLog(@"%@",myStr);
                    
                    if(ctx != nil) {
                        FREDispatchStatusEventAsync(ctx, (uint8_t*)"CHANGE", (uint8_t*)[myStr UTF8String]); 
                    }
                    
                    myStr = nil;
                }
                
            };
            
            [motionManager startGyroUpdatesToQueue:opQ withHandler:gyroHandler]; 
            //NSLog(@"Gyroscope started");
            ret = YES;
            */
            
                CMDeviceMotionHandler motionHandler = ^ (CMDeviceMotion *devMotion, NSError *error) {
                
					if (ctx != nil) {
						//CMRotationRate rotate = gyroData.rotationRate;                        
						NSString *myStr = [NSString stringWithFormat:@"%f&%f&%f", devMotion.attitude.roll, devMotion.attitude.pitch, devMotion.attitude.yaw]; 
						//NSLog(@"%@",myStr);
                        
						if(ctx != nil) {
							FREDispatchStatusEventAsync(ctx, (uint8_t*)"CHANGE", (uint8_t*)[myStr UTF8String]); 
						}
                        
						myStr = nil;
					}
					
				};
                
			    //[motionManager startGyroUpdatesToQueue:opQ withHandler:gyroHandler];
                [motionManager startDeviceMotionUpdatesToQueue:opQ withHandler:motionHandler];
			    //NSLog(@"Euler Gyroscope started");
			    ret = YES;
             
		} 
        
        else {
        
			[motionManager release];
			ret = NO;
		}
        
	}
    
    else {
    
		ret = NO;
		//NSLog(@"Euler motionManager was NULL. Something is very wrong");
	}

	FRENewObjectFromBool(ret, &retVal);
    
    //NSLog(@"Exiting Euler startGyro()");
    
	return retVal;
}



// stopGyro() 
//
// Called from the dispose() method of ActionScript class Gyroscope.

FREObject KTZEulerGyrostopGyro(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[]) {

    //NSLog(@"Euler Entering stopGyro()");
    BOOL ret = NO;
    
	FREObject retVal;
    
	[motionManager stopGyroUpdates];
    
	//NSLog(@"Euler gyroScope Stopped");

	FRENewObjectFromBool(ret,&retVal);  
	
    //NSLog(@"Euler Exiting stopGyro()");
	
	return retVal; 
}



// supportGyro() 
//
// Called from the isSupported() method of ActionScript class Gyroscope.

FREObject KTZEulerGyrosupportGyro(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[]) {

	//NSLog(@"Euler Entering supportGyro()");
    
	BOOL ret = NO;
    
	if (motionManager != nil) {
    
		ret = motionManager.gyroAvailable;
	}
    
	FREObject retVal;
	FRENewObjectFromBool(ret, &retVal);
    
    //NSLog(@"Euler Exiting supportGyro()");
	return retVal;
}



// initStub()
//
// An init function is necessary in the Android implementation of this extension.
// Therefore, an analogous function is necessary in the iOS implementation to make
// the ActionScript interface identical for all implementations.
// However, the iOS implementation has nothing to do.

FREObject KTZEulerGyroinitStub(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[]) {

	//NSLog(@"Euler init Stub Called");
	return nil;
}



// ContextInitializer() 
//
// The context initializer is called when the runtime creates the extension context instance.

void KTZEulerGyroContextInitializer(void* extData, const uint8_t* ctxType, FREContext ctx, 
						   uint32_t* numFunctionsToTest, const FRENamedFunction** functionsToSet) {
                           
    //NSLog(@"Euler Entering ContextInitializer()");
                           
	*numFunctionsToTest = 4;
	FRENamedFunction* func = (FRENamedFunction*)malloc(sizeof(FRENamedFunction) * 4);
    
	func[0].name = (const uint8_t*)"KTZEulerGyroStart";
	func[0].functionData = NULL;
	func[0].function = &KTZEulerGyrostartGyro;

	func[1].name = (const uint8_t*)"KTZEulerGyroStop";
	func[1].functionData = NULL;
	func[1].function = &KTZEulerGyrostopGyro;

	func[2].name = (const uint8_t*)"KTZEulerGyroSupport";
	func[2].functionData = NULL;
	func[2].function = &KTZEulerGyrosupportGyro;
	
	func[3].name = (const uint8_t*)"KTZEulerGyroInit";
	func[3].functionData = NULL;
	func[3].function = &KTZEulerGyroinitStub;
	
	*functionsToSet = func; 
	
	motionManager = [[CMMotionManager alloc] init];
    motionManager.gyroUpdateInterval = 0;
    motionManager.deviceMotionUpdateInterval = 0;
	
	opQ = [[NSOperationQueue currentQueue] retain];  
	
    //NSLog(@"Euler Exiting ContextInitializer()");
}



// ContextFinalizer()
//
// The context finalizer is called when the extension's ActionScript code
// calls the ExtensionContext instance's dispose() method.
// If the AIR runtime garbage collector disposes of the ExtensionContext instance, the runtime also calls
// ContextFinalizer().

void KTZEulerGyroContextFinalizer(FREContext ctx) { 

    //NSLog(@"Euler Entering ContextFinalizer()");
    
	[motionManager release];
	[opQ release];
	motionManager = nil;
	opQ = nil;
    
    //NSLog(@"Euler Exiting ContextFinalizer()");
	
}



// ExtInitializer()
//
// The extension initializer is called the first time the ActionScript side of the extension
// calls ExtensionContext.createExtensionContext() for any context.

void KTZEulerGyroExtInitializer(void** extDataToSet, FREContextInitializer* ctxInitializerToSet, 
					FREContextFinalizer* ctxFinalizerToSet) {
                    
    //NSLog(@"Euler Entering ExtInitializer()");                    
                    
	*extDataToSet = NULL;
	*ctxInitializerToSet = &KTZEulerGyroContextInitializer; 
	*ctxFinalizerToSet = &KTZEulerGyroContextFinalizer;
    
    //NSLog(@"Euler Exiting ExtInitializer()"); 
}  



// ExtFinalizer()
//
// The extension finalizer is called when the runtime unloads the extension. 
// However, it is not always called.

void KTZEulerGyroExtFinalizer(void* extData) {

    //NSLog(@"Euler Entering ExtFinalizer()");
	return;
}
